<template>
  <div id="rulesModification">
    <el-form class="configuration" ref="rulesMessage" :model="form.data" label-position="top">
      <div class="communicationitem" v-for="(item, index) in form.data.inbound_permissions" :key="index">
        <el-icon :class="form.data.inbound_permissions.length > 1 ? 'minus' : 'none'" @click="minusport(index)"><Close /></el-icon>
        <div class="col1">
          <el-form-item label="网络协议" :prop="'inbound_permissions.' + index + '.protocol'" :rules="configuration_rules.protocol">
            <el-select v-model="item.protocol"> <el-option v-for="i in protocol_options" :key="i.value" :label="i.label" :value="i.value" /> </el-select
          ></el-form-item>
        </div>
        <div class="col2">
          <el-form-item label="IP地址" :prop="'inbound_permissions.' + index + '.ip_range'" :rules="configuration_rules.ip_range">
            <el-input v-model="item.ip_range" minlength="9" maxlength="18" />
          </el-form-item>
        </div>
        <div class="col3">
          <el-form-item label="开始端口" :prop="'inbound_permissions.' + index + '.from_port'" :rules="configuration_rules.from_port">
            <div style="display: flex">
              <el-input v-model.number="item.from_port" />
              <span class="portline">———</span>
            </div>
          </el-form-item>
          <div class="toport">
            <el-form-item label="结束端口" :prop="'inbound_permissions.' + index + '.to_port'" :rules="configuration_rules.to_port">
              <el-input v-model.number="item.to_port" />
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="add">
        <el-button class="btn button" @click="addport">+&nbsp;新增栏</el-button>
      </div>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
  #rulesModification {
    .communicationitem {
      height: 240px;
      border: 1px solid #e0e2e9;
      border-radius: 2px;
      padding: 24px 20px 6px 20px;
      margin-bottom: 20px;
      .none {
        display: none;
      }
      .minus {
        float: right;
        cursor: pointer;
      }
      .el-input {
        width: 480px;
      }
      .el-select {
        width: 320px;
      }
      :deep(.el-input__wrapper) {
        font-size: 12px;
      }
      .col3 {
        display: inline-flex;
        .el-input {
          width: 210px;
        }
        .portline {
          width: 40px;
          color: #e0e2e9;
        }
      }
    }
    .button {
      width: 100px;
      height: 28px;
    }
  }
</style>
<script lang="ts" setup>
  import appStore from '@/store'
  import Vue, { onMounted, ref, reactive, watch } from 'vue'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import FleetsService, { FleetRulesMsg, UpdateFleetInboundPermissionsRequest } from '@/api/fleetsService'
  import fleetDetails, { ProcessParamType } from '@/api/fleetDetails'
  import _ from 'lodash'
  import { ElMessageBox } from 'element-plus'

  const rulesMessage = ref<FormInstance>()
  let old_inbound_permissions: any[] = []

  let formData = reactive({
    inbound_permissions: [Object()]
  })

  let form = reactive({
    data: formData
  })

  const emits = defineEmits(['close', 'get'])
  const props = defineProps(['fleetId'])
  let fleet_id = props.fleetId

  watch(
    () => props.fleetId,
    (newValue, oldValue) => {
      fleet_id = newValue
    }
  )

  const getFleet: ProcessParamType = {
    project_id: appStore.userStore.project_id,
    fleet_id: fleet_id
  }

  const submitForm: FleetRulesMsg = {
    project_id: appStore.userStore.project_id,
    fleet_id: fleet_id,
    UpdateFleetInboundPermissionsRequestBody: {
      inbound_permission_authorizations: [],
      inbound_permission_revocations: []
    }
  }

  const protocol_options = [
    {
      value: 'TCP',
      label: 'TCP'
    },
    {
      value: 'UDP',
      label: 'UDP'
    }
  ]

  const portValidate = (rule: any, value: any, callback: any) => {
    let index = Number(rule.field.split('.')[1])
    if (form.data.inbound_permissions[index] !== undefined) {
      if (form.data.inbound_permissions[index].to_port <= form.data.inbound_permissions[index].from_port) {
        callback(new Error('起始端口要小于终止端口'))
      } else {
        callback()
      }
    }
  }

  const configuration_rules = reactive<FormRules>({
    protocol: [{ required: true, message: '请选择协议', trigger: 'blur' }],
    ip_range: [{ required: true, message: '请输入IP', trigger: 'blur' }],
    from_port: [
      { required: true, type: 'number', min: 1025, max: 60000, message: '请输入1025-60000范围内的数字', trigger: 'blur' },
      { validator: portValidate, trigger: 'blur' }
    ],
    to_port: [
      { required: true, type: 'number', min: 1025, max: 60000, message: '请输入1025-60000范围内的数字', trigger: 'blur' },
      { validator: portValidate, trigger: 'blur' }
    ]
  })

  const getFleetInboundPermissions = async () => {
    let res = await fleetDetails.getInbound(getFleet)
    form.data.inbound_permissions = res.data.inbound_permissions
    old_inbound_permissions = JSON.parse(JSON.stringify(res.data.inbound_permissions))
  }

  const getSubmitData = () => {
    form.data.inbound_permissions.forEach((item) => {
      var index = _.findIndex(old_inbound_permissions, function (o) {
        return _.isEqual(o, item)
      })
      if (index !== -1) {
        old_inbound_permissions.splice(index, 1)
      } else {
        submitForm.UpdateFleetInboundPermissionsRequestBody.inbound_permission_authorizations.push(item)
      }
    })
    if (old_inbound_permissions.length > 0) {
      submitForm.UpdateFleetInboundPermissionsRequestBody.inbound_permission_revocations = JSON.parse(JSON.stringify(old_inbound_permissions))
    }
  }
  const submit = async () => {
    let res = await FleetsService.updateRules(submitForm)
    if (res.status === 204) {
      ElMessage({
        message: '修改成功！',
        type: 'success'
      })
      emits('get')
      emits('close')
    }
  }
  const onSubmit = async () => {
    getSubmitData()
    var rulesMessageValid = await rulesMessage.value?.validate((valid) => {
      return valid
    })
    if (rulesMessageValid) {
      ElMessageBox.confirm('请确定保存修改吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          submit()
        })
        .catch(() => {})
    }
  }

  defineExpose({ onSubmit })

  const minusport = (index: number) => {
    if (form.data.inbound_permissions.length < 2) return
    form.data.inbound_permissions.splice(index, 1)
  }

  const addport = () => {
    if (form.data.inbound_permissions.length > 49) return
    form.data.inbound_permissions.push(Object())
  }

  onMounted(() => {
    getFleetInboundPermissions()
  })
</script>
